package net.suncaper.mvc.mapper.impl;

import net.suncaper.mvc.mapper.RoleMapper;
import net.suncaper.mvc.model.domain.Role;
import net.suncaper.mvc.model.domain.RolePermission;
import net.suncaper.mvc.model.domain.UserRole;
import net.suncaper.mvc.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Role表数据库访问接口实现类
 */
public class RoleMapperImpl implements RoleMapper {
    private static final QueryRunner RUNNER = new QueryRunner();

    /**
     * 新增角色信息
     *
     * @param role 角色信息
     * @return 新增结果
     */
    @Override
    public boolean insertRole(Role role) {
        String sql = "INSERT INTO role(role_id, role_name) VALUES (?, ?)";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    role.getRoleId(), role.getRoleName()
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 根据角色ID查询角色信息
     *
     * @param roleId 角色ID
     * @return 角色信息
     */
    @Override
    public Role selectRoleById(Integer roleId) {
        String sql = "SELECT * FROM role WHERE role_id = ?";
        Connection connection = JDBCUtils.getConnection();
        Role role = null;
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setInt(1, roleId);
            rs = ps.executeQuery();
            if (rs.next()) {
                role = new Role();
                role.setRoleId(rs.getInt("role_id"));
                role.setRoleName(rs.getString("role_name"));
                System.out.println("[selectRoleById] role_id=" + rs.getInt("role_id") + ", role_name=" + rs.getString("role_name"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            JDBCUtils.close();
        }
        return role;
    }

    /**
     * 根据角色名称查询角色信息
     *
     * @param roleName 角色名称
     * @return 角色信息
     */
    @Override
    public Role selectRoleByName(String roleName) {
        String sql = "SELECT * FROM role WHERE role_name = ?";
        Connection connection = JDBCUtils.getConnection();
        Role role = null;
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1, roleName);
            rs = ps.executeQuery();
            if (rs.next()) {
                role = new Role();
                role.setRoleId(rs.getInt("role_id"));
                role.setRoleName(rs.getString("role_name"));
                System.out.println("[selectRoleByName] role_id=" + rs.getInt("role_id") + ", role_name=" + rs.getString("role_name"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            JDBCUtils.close();
        }
        return role;
    }

    /**
     * 查询所有角色信息
     *
     * @return 角色列表
     */
    @Override
    public List<Role> selectAllRoles() {
        String sql = "SELECT * FROM role";
        Connection connection = JDBCUtils.getConnection();
        java.util.List<Role> roles = new java.util.ArrayList<>();
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                Role role = new Role();
                role.setRoleId(rs.getInt("role_id"));
                role.setRoleName(rs.getString("role_name"));
                System.out.println("[selectAllRoles] role_id=" + rs.getInt("role_id") + ", role_name=" + rs.getString("role_name"));
                roles.add(role);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            JDBCUtils.close();
        }
        return roles;
    }

    /**
     * 更新角色信息
     *
     * @param role 角色信息
     * @return 更新结果
     */
    @Override
    public boolean updateRole(Role role) {
        String sql = "UPDATE role SET role_name = ? WHERE role_id = ?";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    role.getRoleName(), role.getRoleId()
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 删除角色信息
     *
     * @param roleId 角色ID
     * @return 删除结果
     */
    @Override
    public boolean deleteRole(Integer roleId) {
        String sql = "DELETE FROM role WHERE role_id = ?";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    roleId
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 为角色分配权限
     *
     * @param rolePermission 角色权限关联信息
     * @return 分配结果
     */
    @Override
    public boolean assignPermissionToRole(RolePermission rolePermission) {
        String sql = "INSERT INTO role_permission(role_id, permission_id) VALUES (?, ?)";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    rolePermission.getRoleId(), rolePermission.getPermissionId()
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 为用户分配角色
     *
     * @param userRole 用户角色关联信息
     * @return 分配结果
     */
    @Override
    public boolean assignRoleToUser(UserRole userRole) {
        String sql = "INSERT INTO user_role(user_id, role_id, hotel_name) VALUES (?, ?, ?)";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    userRole.getUserId(), userRole.getRoleId(), userRole.getHotelName()
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 根据用户ID查询用户的角色列表
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<Role> selectRolesByUserId(String userId) {
        String sql = "SELECT r.* FROM role r JOIN user_role ur ON r.role_id = ur.role_id WHERE ur.user_id = ?";
        Connection connection = JDBCUtils.getConnection();
        java.util.List<Role> roles = new java.util.ArrayList<>();
        java.sql.PreparedStatement ps = null;
        java.sql.ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1, userId);
            rs = ps.executeQuery();
            while (rs.next()) {
                Role role = new Role();
                role.setRoleId(rs.getInt("role_id"));
                role.setRoleName(rs.getString("role_name"));
                System.out.println("[selectRolesByUserId] role_id=" + rs.getInt("role_id") + ", role_name=" + rs.getString("role_name"));
                roles.add(role);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (ps != null) ps.close(); } catch (Exception e) {}
            JDBCUtils.close();
        }
        return roles;
    }

    /**
     * 移除用户的角色
     *
     * @param userId 用户ID
     * @param roleId 角色ID
     * @return 移除结果
     */
    @Override
    public boolean removeRoleFromUser(String userId, Integer roleId) {
        String sql = "DELETE FROM user_role WHERE user_id = ? AND role_id = ?";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    userId, roleId
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 移除角色的权限
     *
     * @param roleId 角色ID
     * @param permissionId 权限ID
     * @return 移除结果
     */
    @Override
    public boolean removePermissionFromRole(Integer roleId, Integer permissionId) {
        String sql = "DELETE FROM role_permission WHERE role_id = ? AND permission_id = ?";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    roleId, permissionId
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }
} 